from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, RetrieveAPIView, DestroyAPIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import BaseFilterBackend

from api.models import Article, ArticleDetail
from api.serializer import *


class CategoryFilterBackend(BaseFilterBackend):
    # 当分类时过滤
    def filter_queryset(self, request, queryset, view):
        category = request.query_params.get('category')
        if category:
            return queryset.filter(category=category)
        else:
            return queryset


class ArticleView(ListAPIView, CreateAPIView):
    queryset = Article.objects.all()
    filter_backends = [CategoryFilterBackend, ]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ArticleSerializer
        elif self.request.method == 'POST':
            return PostArticleSerializer

    def perform_create(self, serializer):
        author = self.request.user
        article_obj = serializer.save(author=author)
        ser = ArticleDetailSerializer(data=self.request.data)
        if ser.is_valid():
            ser.save(article=article_obj, author=author)


class ArticleDetailView(RetrieveAPIView, UpdateAPIView, DestroyAPIView):
    queryset = Article.objects.all()

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return FullArticleSerializer
        else:
            return PostArticleSerializer

    def perform_update(self, serializer):
        author = self.request.user
        article_pk = self.kwargs.get('pk')
        article_obj = Article.objects.filter(pk=article_pk).first()
        detail_obj = ArticleDetail.objects.filter(article=article_obj).first()
        if self.request.data.get('content'):
            ser = ArticleDetailSerializer(instance=detail_obj, data=self.request.data, partial=True)
            if ser.is_valid():
                ser.save( article=article_obj)
        serializer.save(author=author)


